package com.zuoshenge.sys.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zuoshenge.sys.bean.JwtProperties;
import com.zuoshenge.sys.expection.BadRequestException;
import com.zuoshenge.sys.expection.TokenExpiredException;
import com.zuoshenge.sys.utils.JwtTokenUtil;
import com.zuoshenge.sys.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import org.apache.tomcat.Jar;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Key;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Configuration
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
//        String rememberMeToken = request.getHeader("RememberMeToken");
        // 获取请求的URI
        String requestURI = request.getRequestURI();
        System.out.println("请求uri " + requestURI);
        System.out.println("请求urL" + request.getRequestURL());
        // 定义不需要Token验证的路径
//        List<String> exemptPaths = Arrays.asList("/auth/login", "/auth/register");
        // 检查请求路径是否在免验证列表中
//        if (exemptPaths.stream().anyMatch(requestURI::contains)) {
//            System.out.println("登录注册请求被拦截");
//            // 如果是/auth/login或/auth/register请求，则跳过Token验证
//            // 这里可以添加其他逻辑，如重定向、记录日志等
//            if (rememberMeToken != null && !rememberMeToken.isEmpty()) {
//                System.out.println("rememberMeToken不空");
//                redisUtil.updateKeyTtl(jwtTokenUtil.rememberKey(rememberMeToken),jwtProperties.getRememberMeTokenValidityInSeconds(),
//                        TimeUnit.MILLISECONDS);
//            }
//            return true; // 继续处理请求
//        }
        // TODO 针对get请求中传递username的情况，把username和token进行比较，看看是否对的上

        if (token != null && !StringUtils.isBlank(token)) {
            byte[] keyBytes = Decoders.BASE64.decode(jwtProperties.getBase64Secret());
            Key key = Keys.hmacShaKeyFor(keyBytes);
            token = token.substring(7);
//        Claims claims = Jwts.parser()
//                .setSigningKey(keyBytes) // 使用你的原始密钥字节数组
//                .parseClaimsJws(token)
//                .getBody();
//
//        // 从这里开始，你可以从claims中获取你需要的信息，比如用户名等
//        String username2 = claims.getSubject();
//        System.out.println("username2" + username2);
            System.out.println("获取到的token：" + token);
            if (StringUtils.isBlank(token)) {
                throw new BadRequestException("token为空");
            }
            if (redisUtil.get(jwtTokenUtil.loginKey(token)) == null || StringUtils.isBlank((String)redisUtil.get(jwtTokenUtil.loginKey(token)))) {
                throw new TokenExpiredException("登录状态过期，请重新登录");
            }
            redisUtil.updateKeyTtl(jwtTokenUtil.loginKey(token),jwtProperties.getTokenValidityInSeconds(), TimeUnit.MILLISECONDS);
        }
        return true;
    }
}